// Sock.h: interface for the CSock class.
//
//////////////////////////////////////////////////////////////////////

#pragma once

#include "define.h"

#ifdef WIN32  
	//#include <windows.h>
	#include <winsock2.h>
	#include <string.h>

	#pragma comment( lib, "ws2_32.lib" )

#else
	#include <stdio.h>
	#include <unistd.h>
	#include <stdlib.h>
	#include <string.h>

	#include <sys/socket.h>
	#include <sys/stat.h>	
	#include <sys/types.h>
	#include <arpa/inet.h>
	#include <sys/time.h>	

	#define SLEEP(n) usleep(n);	

#endif

class CSock
{
	
public:

	typedef int SOCKET;

	enum
	{
		TCP = 1,
		UDP = 2,

		DEF_BACKLOG = 5,

		MAXBUFF = 128,

		MAX_FDSIZE = FD_SETSIZE,
		MAX_TIMEOUT = 5,
	};

	
	
	CSock();
	virtual ~CSock();

	int Init( int nType = 0 );
	int Connect( char* szIP, size_t nPort );
	
	int Bind( size_t nPort, char* szIP = 0 );
	int Listen( size_t nBackLog = 0 );
	int Accept( CSock& PeerSock );

	int SetReuseAddr( bool isEnable );
	int SetLinger( bool isEnable, int nWaitTime );

	int SetSockOpt( int nLevel, int nOptName, void* pOptVal, int nOptValLen );
	int GetSockOpt( int nLevel, int nOptName, void* pOptVal, socklen_t* pnOptValLen );

	int Send( char* szMsg, size_t nLen );
	int Recv( char* szMsg, size_t nLen );

	int Send_udp( CSock& PeerSock, char* szMsg, size_t nLen, int nFlag = 0 );
	int Recv_udp( CSock& PeerSock, char* szMsg, size_t nLen, int nFlag = 0 );

	int Close();

	void SetAddr( struct sockaddr_in* addr ) { memcpy(&m_Addr, addr, sizeof(sockaddr_in) ); }
	void SetSocket( SOCKET sock ) { m_Sock = sock; }

	const SOCKET GetSock() const { return m_Sock; }
	const struct sockaddr_in* GetAddr() const { return &m_Addr; }

	const int GetType() const { return m_nType; }
	void SetType( const int nType )
	{
		if( (0 > nType) || ( UDP < nType ) ) 
			m_nType = TCP;
		else
			m_nType = nType;
	}

private:
	
	SOCKET					m_Sock;
	int						m_nType;

	struct	sockaddr_in		m_Addr;
};

